#!/usr/bin/env python3 
# -*- coding:UTF8 -*-
import cv2 as cv

def cutMatUp(img, val):
    h, w = img.shape[:2]
    iCount = 0
    for i in range(h):
        count = 0
        for j in range(w):
            if img[i][j] == val:
                count += 1
            if count >= w * 0.15:
                return img[iCount:h, 0:w]
        else:
            iCount += 1

def cutMatDown(img, val):
    h, w = img.shape[:2]
    iCount = 0
    for i in reversed(range(h)):
        count = 0
        for j in range(w):
            if img[i][j] == val:
                count += 1
            if count >= w * 0.2:
                return img[:h - iCount, :w]
        else:
            iCount += 1

def cutMapLeft(img, val):
    h, w = img.shape[:2]
    iCount = 0
    for i in range(w):
        count = 0
        for j in range(h):
            if img[j][i] == val:
                count += 1
            if count >= h * 0.2:
                return img[0:h, iCount:w]
        else:
            iCount += 1

def cutMatRight(img, val):
    h, w = img.shape[:2]
    iCount = 0
    for i in reversed(range(w)):
        count = 0
        for j in range(h):
            if img[j][i] == val:
                count += 1
            if count >= h * 0.2:
                return img[0:h, 0:w - iCount]
        else:
            iCount += 1

def clearLiuDing(gray):
    h, w = gray.shape[:2]
    count = 0
    jump = []
    for i in range(h):
        jumpCount = 0
        for j in range(0, w - 1):
            if gray[i][j] != gray[i][j + 1]:
                jumpCount += 1
            if gray[i][j] == 255:
                count += 1
        jump.append(jumpCount)
    iCount = 0
    for i in range(h):
        if jump[i] >= 16 and jump[i] <= 45:
            iCount += 1
    if (count * 1.0 / (h * w) < 0.15 or count * 1.0 / (h * w) > 0.50):
        return False
    for i in range(h):
        if jump[i] <= 7:
            for j in range(w):
                gray[i][j] = 0
    return True


def splitContour(img):
    contours, hierarchy = cv.findContours(img, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)[-2:]
    d = {}
    for i in range(len(hierarchy[0])):
        if (hierarchy[0][i][0] != -1 and hierarchy[0][i][3] == -1) or (
                hierarchy[0][i][0] == -1 and hierarchy[0][i][1] != -1 and hierarchy[0][i][3] == -1):
            x, y, w, h = cv.boundingRect(contours[i])
            if w < 5 or h < 20:
                continue
            temp = img[y:y + h, x:x + w]
            temp = cv.resize(temp, (20, 20))
            d.update({str(x): temp})
    return d

def test():
    import os
    from ai_library.components import findPlate
    import numpy as np
    imagePath = './download'
    for img_path in os.listdir(imagePath):
        img_path = os.path.join(imagePath, img_path)
        img = cv.imread(img_path)
        img_plate  = findPlate.detect(img)
        gray = cv.cvtColor(img_plate, cv.COLOR_BGR2GRAY)
        ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
        # cv.imshow('binary', binary)
        upImg = cutMatUp(binary, 0)
        downImg = cutMatDown(upImg, 0)
        leftImg = cutMapLeft(downImg, 0)
        rightImg = cutMatRight(leftImg, 0)
        h, w = rightImg.shape[:2]
        temp = rightImg[int(0.020 * h):int(h * 0.97), int(0.020 * w): int(0.98 * w)]
        clearLiuDing(temp)
        upImg = cutMatUp(temp, 255)
        downImg = cutMatDown(upImg, 255)
        leftImg = cutMapLeft(downImg, 255)
        rightImg = cutMatRight(leftImg, 255)
        # cv.imshow('up', rightImg)
        resize = cv.resize(rightImg, (144, 34), interpolation = cv.INTER_AREA)
        cv.imshow('test', resize)
        cv.waitKey(2000)
        d = splitContour(resize)
        for img in d.values():
            cv.imshow('zi', img)
            cv.waitKey(500)
        cv.destroyWindow('zi')

def main():
    test()

if __name__ == '__main__':
    main()